package cn.breeze.pet.service.impl;

import cn.breeze.basic.dto.HandlerMsgDto;
import cn.breeze.basic.exception.BusinessException;
import cn.breeze.basic.utils.*;
import cn.breeze.order.domain.OrderPetAcquisition;
import cn.breeze.order.mapper.OrderPetAcquisitionMapper;
import cn.breeze.org.domain.Shop;
import cn.breeze.org.mapper.ShopMapper;
import cn.breeze.pet.domain.*;
import cn.breeze.pet.mapper.PetMapper;
import cn.breeze.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.breeze.pet.mapper.SearchMasterMsgMapper;
import cn.breeze.pet.service.ISearchMasterMsgService;
import cn.breeze.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author breeze
 * @since 2022-07-18
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
    * @Title: publish
    * @Description: 宠物寻主
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/19 16:23
    * @Parameters: [msg]
    * @Return void
    */
    @Override
    public void publish(SearchMasterMsg msg) {
        // 保存寻主信息
        searchMasterMsgMapper.save(msg);
        // 百度AI审核图片和文本信息
        StringBuffer str = new StringBuffer().append(msg.getName())
                .append(msg.getNote())
                .append(msg.getTitle())
                .append(msg.getAddress());
        if (!BaiduAuditUtils.TextCensor(str.toString())){
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(msg.getId());
            searchMasterMsgAuditLog.setState(0);
            searchMasterMsgAuditLog.setAuditTime(new Date());
            searchMasterMsgAuditLog.setNote("文本不合规：可能是标题、昵称、毛色、地址");
            searchMasterMsgAuditLogMapper.save(searchMasterMsgAuditLog);
        } else {
            msg.setState(1);
            // 匹配附近我们50km的店铺
            List<Shop> shops = shopMapper.loadAll();
            Point point = DistanceUtil.getPoint(msg.getAddress());
            Shop shop = DistanceUtil.getNearestShop(point, shops);
            if (shop != null){
                msg.setShopId(shop.getId());
            }
        }
        searchMasterMsgMapper.update(msg);
    }

    /**
    * @Title: accept
    * @Description: 店铺员接单
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/20 14:52
    * @Parameters: [handlerMsgDto]
    * @Return void
    */
    @Override
    public void accept(HandlerMsgDto handlerMsgDto) {
        Long handler = handlerMsgDto.getHandler();
        Long msgId = handlerMsgDto.getMsgId();
        String note = handlerMsgDto.getNote();
        // 判断参非空
        if (handler == null || msgId == null || StringUtils.isEmpty(note)){
            throw new BusinessException("参数非法，请重新传递！");
        }
        // 判断该消息是否已被接收
        // 格局消息id去查询订单是否存在
        OrderPetAcquisition orderPetAcquisition = orderPetAcquisitionMapper.loadByMsgIdAndNotCanceled(msgId);
        if (orderPetAcquisition != null){
            throw new BusinessException("该订单已被接单！");
        }
        // 生成宠物基本信息
        // 获取到寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        // 初始化宠物对象
        Pet pet = msgToPet(msgId, searchMasterMsg);
        // 保存宠物
        petMapper.save(pet);
        // 生成收购单
        orderPetAcquisition = initOrderPetAcquisition(handler, msgId, note, searchMasterMsg, pet);
        // 保存收购单
        orderPetAcquisitionMapper.save(orderPetAcquisition);
        // 发送延迟消息
        Map<String,Object> orderMap = new HashMap<>();
        orderMap.put("orderNumber",orderPetAcquisition.getOrderSn());
        orderMap.put("createTime", new Date());
        rocketMQTemplate.syncSend("order-topic-delay", MessageBuilder.withPayload(JSONObject.toJSONString(orderMap)).build(),3000,19);

    }

    /**
    * @Title: reject
    * @Description: 拒绝接单
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/20 16:36
    * @Parameters: [id]
    * @Return void
    */
    @Override
    public void reject(Long id) {
        // 根据id去查询
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(id);
        if (searchMasterMsg == null){
            throw new BusinessException("非法参数！");
        }
        searchMasterMsg.setShopId(null);
        searchMasterMsg.setUserId(null);
        // 修改店铺id为null，将当前消息放入到寻主池
        searchMasterMsgMapper.update(searchMasterMsg);
    }

    /**
    * @Title: initOrderPetAcquisition
    * @Description: 初始化OrderPetAcquisition
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/20 16:29
    * @Parameters: [handler, msgId, note, searchMasterMsg, pet]
    * @Return cn.breeze.order.domain.OrderPetAcquisition
    */
    private OrderPetAcquisition initOrderPetAcquisition(Long handler, Long msgId, String note, SearchMasterMsg searchMasterMsg, Pet pet) {
        OrderPetAcquisition orderPetAcquisition;
        orderPetAcquisition = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msgId);
        orderPetAcquisition.setOrderSn(orderSn);
        orderPetAcquisition.setDigest(note);
        orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis() + 2*24*60*60*1000));
        orderPetAcquisition.setPrice(searchMasterMsg.getPrice());
        orderPetAcquisition.setPaytype(0);
        orderPetAcquisition.setPetId(pet.getId());
        orderPetAcquisition.setUserId(searchMasterMsg.getUserId());
        orderPetAcquisition.setShopId(searchMasterMsg.getShopId());
        orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
        orderPetAcquisition.setEmpId(handler);
        orderPetAcquisition.setSearchMasterMsgId(msgId);
        return orderPetAcquisition;
    }

    /**
    * @Title: msgToPet
    * @Description: 将msg赋值到pet
    * @Author: Mr.D
    * @Version: 1.0
    * @Date:  2022/7/20 16:28
    * @Parameters: [msgId, searchMasterMsg]
    * @Return cn.breeze.pet.domain.Pet
    */
    private Pet msgToPet(Long msgId, SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setCostprice(searchMasterMsg.getPrice());
        pet.setTypeId(searchMasterMsg.getPetType());
        pet.setResources(searchMasterMsg.getResources());
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setSearchMasterMsgId(msgId);
        return pet;
    }
}
